﻿$(function($) {
   // alert(gPageParam.processPage.DriverType);
  //  alert(gPageParam.processPage.ChannelType);
  //initDriverFields(gPageParam.processPage.DriverType);
 // initChannelFields(gPageParam.processPage.ChannelType);
  initPropertyGrid("channel",gPageParam.processPage.ChannelType);
   initPropertyGrid("driver",gPageParam.processPage.DriverType);
   
});

//表格显示需要的数据  *Type 为显示dropdownlist需要的数据
var gridProperty = {
    driver: {
        datafields: [],
        columns: [],
        emunList: {} //gridproperty.emunlist[field]=[];
    },
    channel: {
        datafields: [],
        columns: [],
        emunList: {} //gridproperty.emunlist[field]=[];
    },

};
//初始话工具栏懒妞
function initToolBar() {

    $("#tool_add").on("click", function() {
        var commit = table.jqxGrid('addrow', null, {});
        //alert(getdataAdapte.driverlist);
    });

    $("#tool_delete").on("click", function() {
        var selectedrowindex = table.jqxGrid('getselectedrowindex');
        var rowscount = table.jqxGrid('getdatainformation').rowscount;
        if (selectedrowindex >= 0 && selectedrowindex < rowscount) {
            var id = table.jqxGrid('getrowid', selectedrowindex);
            var commit = table.jqxGrid('deleterow', id);
        }
    });

}



//加载配置文件，并形成界面
function initDriverFields(driverType) {

    var source = {
        datatype: "xml",
        datafields: [{
            name: 'Desc',
            map: 'm\\:properties>d\\:Desc'
        }, {
            name: 'Field',
            map: 'm\\:properties>d\\:Field'
        }, {
            name: 'DefaultValue',
            map: 'm\\:properties>d\\:DefaultValue'
        }, {
            name: 'DataType',
            map: 'm\\:properties>d\\:DataType'
        }, {
            name: 'Enum',
            map: 'm\\:properties>d\\:EnumData' //在低版本中，xml的项必须存在，且不能为空，高版本中可以不存在，且能为空，所以在没有枚举量的xml项中补填N作为占位
        }],
        root: "content",
        // record : "content",
        id: 'm\\:properties>d\\:Field',
        url: "table_xml/" + driverType + ".xml"
    };
    //加载配置文件
    var dataAdapter = new $.jqx.dataAdapter(source, {
		autoBind:true,
        loadComplete: function() {
            // get data records.
            var records = dataAdapter.records;
            var length = records.length;
            for (var i = 0; i < length; i++) {
                var record = records[i];
                var fields = {};
                fields["name"] = record.Field;
                gridProperty.driver.datafields.push(fields);

                var column = {};
                column["datafield"] = record.Field;
                column["text"] = record.Desc;

                if (record.DataType.indexOf("Enum") > -1) //直接判断== 也可以，为了防止字符串中的空格

                {
                    column["columntype"] = 'dropdownlist';


                    try {
                        gridProperty.driver.emunList[record.Field] = [];
                        // eval('(' + record.Enum + ')')     字符串转换json的另一种方法                            
                        var enumval = jQuery.parseJSON(record.Enum); //将枚举类型的json字符串转换为json对象，
                        // $(enumval).each(function(feild,text){
                        $.each(enumval, function(value, text) { //遍历json对象，形成dropdownlist需要的source对象
                            var item = {};
                            item["value"] = value;
                            item["text"] = text;
                            // alert(feild+"=="+value);
                            gridProperty.driver.emunList[record.Field].push(item);
                        });
                    } catch (e) {

                    }
                    column["createeditor"] = function(row, column, editor) {
                        // assign a new data source to the dropdownlist.

                        editor.jqxDropDownList({
                            source: gridProperty.driver.emunList[record.Field],
                            placeHolder: "选择类型:",
                            autoDropDownHeight: true,
                            displayMember: "text",
                            valueMember: "value",
                            theme: theme
                        });

                    };


                    // column ["initEditor"]= function (row, cellvalue, editor, celltext, width, height) {
                    // set the editor's current value. The callback is called each time the editor is displayed.
                    //       editor.jqxDropDownList({ width: width, height: height });

                    //       editor.val(cellvalue);
                    //   };
                }



                column["getEditorValue"] = function(row, cellvalue, editor) {
                    // return the editor's value.
                    return editor.val();
                }

                column["cellvaluechanging"] = function(row, column, columntype, oldvalue, newvalue) {
                    // return the old value, if the new value is empty.
                    if (newvalue == "") return oldvalue;
                }

                column["cellbeginedit"] = function(row, datafield, columntype) {



                    var editableFlag = true;
                    // if ((datafield == "ChannelType") || (datafield == "DriverType")) {
                    //     var useflg = $('#SystemProcess').jqxGrid('getcellvalue', row, "ProcType");

                    //     if (useflg == 0) //proctype==0 标识当前为系统进程，不需要
                    //     {

                    //         editableFlag = false;

                    //     }
                    // }

                    return editableFlag;

                } //end cellbeginedit

                column["cellsrenderer"] = function(row, datafield, value, defaultHtml, columnproperties) {
                    //根据 column->feild column 判断当前列。
                    var editableFlag = true;
                    ////
                    var editableFlag = true;
                    if (gridProperty.driver.emunList[datafiled]) {

                        $.each(gridProperty.driver.emunList[datafield], function(n, val) {
                            if (val.value == value)
                                defaultHtml = val.text;
                        });

                    }

                    if (editableFlag == false) {
                        var element = $(defaultHtml);
                        element.css('color', '#131313');
                        return element[0].outerHTML;
                    }

                    return defaultHtml;

                } //end cellsrenderer

                gridProperty.driver.columns.push(column);
            }

            //================== 表格初始话数据加载完成了之后才初始化 tab，然后在tab的init中初始化表格
            initDriverGrid(driverType);
        }
    });
}

//初始化通道配置表格
function initDriverGrid(type) {

    
    
	alert(gridProperty.driver.datafields);
    var source = {
        datatype: "csv",
        datafields: gridProperty.driver.datafields,
        url: 'defaultData/' + type + '.csv'
    };

    var dataAdapter = new $.jqx.dataAdapter(source, {
        autoBind:true,
        loadError: function(xhr, status, error) {
            alert('Error loading "' + source.url + '" : ' + error);
        }
    });

    var table = $("#channel_property").jqxGrid({
        width: '49%',
        height: '580',
        theme: theme,
        editable: true,
        altrows: true,
        source: dataAdapter,
        //  selectionmode : 'singlecell', //设置选择方式
        columns: gridProperty.driver.columns
    });

    return table;
}


//加载配置文件，并形成界面
function initChannelFields(channeltype) {

    var source = {
        datatype: "xml",
        datafields: [{
            name: 'Desc',
            map: 'm\\:properties>d\\:Desc'
        }, {
            name: 'Field',
            map: 'm\\:properties>d\\:Field'
        }, {
            name: 'DefaultValue',
            map: 'm\\:properties>d\\:DefaultValue'
        }, {
            name: 'DataType',
            map: 'm\\:properties>d\\:DataType'
        }, {
            name: 'Enum',
            map: 'm\\:properties>d\\:EnumData' //在低版本中，xml的项必须存在，且不能为空，高版本中可以不存在，且能为空，所以在没有枚举量的xml项中补填N作为占位
        }],
        root: "content",
        // record : "content",
        id: 'm\\:properties>d\\:Field',
        url: "table_xml/" + channeltype + ".xml"
    };
    //加载配置文件
    var dataAdapter = new $.jqx.dataAdapter(source, {
        loadComplete: function() {
            // get data records.
            var records = dataAdapter.records;
            var length = records.length;
            for (var i = 0; i < length; i++) {
                var record = records[i];
                var fields = {};
                fields["name"] = record.Field;

                gridProperty.channel.datafields.push(fields);

                var column = {};
                column["datafield"] = record.Field;
                column["text"] = record.Desc;

                //   alert(record.DataType);
                if (record.DataType.indexOf("Enum") > -1) //直接判断== 也可以，为了防止字符串中的空格

                {
                    column["columntype"] = 'dropdownlist';
                    try {
                        gridProperty.channel.emunList[record.Field]={};
                        // eval('(' + record.Enum + ')')     字符串转换json的另一种方法                            
                        var enumval = jQuery.parseJSON(record.Enum); //将枚举类型的json字符串转换为json对象，
                        // $(enumval).each(function(feild,text){
                        $.each(enumval, function(value, text) { //遍历json对象，形成dropdownlist需要的source对象
                            var item = {};
                            item["value"] = value;
                            item["text"] = text;
                            // alert(feild+"=="+value);
                            gridProperty.channel.emunList[record.Field].push(item);
                        });
                    } catch (e) {

                    }
                    column["createeditor"] = function(row, column, editor) {
                        // assign a new data source to the dropdownlist.

                        editor.jqxDropDownList({
                            source: gridProperty.channel.emunList[record.Field],
                            placeHolder: "选择进程类型:",
                            autoDropDownHeight: true,
                            displayMember: "text",
                            valueMember: "value",
                            theme: theme
                        });

                    };
                }



                column["getEditorValue"] = function(row, cellvalue, editor) {
                    // return the editor's value.
                    return editor.val();
                }

                column["cellvaluechanging"] = function(row, column, columntype, oldvalue, newvalue) {
                    // return the old value, if the new value is empty.
                    if (newvalue == "") return oldvalue;
                }

                column["cellbeginedit"] = function(row, datafield, columntype) {
                    //获取row对应的datafield的flag的ckeckbox，如果是1，返回true，如果是0，返回false
                    //如果量测启用，前面的所有项才可编辑
                    //这里只有遥测会有这样的配置约束，所以在这里直接填写了遥测dom的div对应的id。在这里取dom的owner的id。不太好弄
                    //波动 Fluc     --对应单元格返回false


                    var editableFlag = true;
              

                    return editableFlag;

                } //end cellbeginedit
                //checkbox 相关的单元格，如果checkbox没有备选中，不允许编辑
                column["cellsrenderer"] = function(row, datafield, value, defaultHtml, columnproperties) {
                    //根据 column->feild column 判断当前列。
                    var editableFlag = true;


                    if (editableFlag == false) {
                        var element = $(defaultHtml);
                        element.css('color', '#131313');
                        return element[0].outerHTML;
                    }

                    return defaultHtml;

                } //end cellsrenderer

                gridProperty.channel.columns.push(column);
            }

            //================== 表格初始话数据加载完成了之后才初始化 tab，然后在tab的init中初始化表格
            initChannelGrid(channeltype);
        }
    });
    dataAdapter.dataBind();

}


function initChannelGrid(type) {

    var source = {
        datatype: "csv",
        datafields: gridProperty.channel.datafields,
        url: 'defaultData/' + type + '.csv'
    };

    var dataAdapter = new $.jqx.dataAdapter(source, {
        async: false,
        loadError: function(xhr, status, error) {
            alert('Error loading "' + source.url + '" : ' + error);
        }
    });

    var table = $("#driver_property").jqxGrid({
        width: '49%',
        height: '580',
        theme: theme,
        editable: true,
        altrows: true,
        source: dataAdapter,
        //  selectionmode : 'singlecell', //设置选择方式
        columns: gridProperty.channel.columns
    });


    return table;
}

///////////////


//加载配置文件，并形成界面
// driverOrchannel  通道或是驱动
// perpertyTye  具体通道或是驱动的类型
function initPropertyGrid(driverOrchannel,propertyType) {

    var source = {
        datatype: "xml",
        datafields: [{
            name: 'Desc',
            map: 'm\\:properties>d\\:Desc'
        }, {
            name: 'Field',
            map: 'm\\:properties>d\\:Field'
        }, {
            name: 'DefaultValue',
            map: 'm\\:properties>d\\:DefaultValue'
        }, {
            name: 'DataType',
            map: 'm\\:properties>d\\:DataType'
        }, {
            name: 'Enum',
            map: 'm\\:properties>d\\:EnumData' //在低版本中，xml的项必须存在，且不能为空，高版本中可以不存在，且能为空，所以在没有枚举量的xml项中补填N作为占位
        }],
        root: "content",
        // record : "content",
        id: 'm\\:properties>d\\:Field',
        url: "table_xml/" + propertyType + ".xml"
    };
    //加载配置文件
    var dataAdapter = new $.jqx.dataAdapter(source, {
        loadComplete: function() {
            // get data records.
            var records = dataAdapter.records;
            var length = records.length;
            for (var i = 0; i < length; i++) {
                var record = records[i];
                var fields = {};
                fields["name"] = record.Field;

                gridProperty[driverOrchannel].datafields.push(fields);

                var column = {};
                column["datafield"] = record.Field;
                column["text"] = record.Desc;

                //   alert(record.DataType);
                if (record.DataType.indexOf("Enum") > -1) //直接判断== 也可以，为了防止字符串中的空格

                {
                    column["columntype"] = 'dropdownlist';
                    try {
                        gridProperty[driverOrchannel].emunList[record.Field]={};
                        // eval('(' + record.Enum + ')')     字符串转换json的另一种方法                            
                        var enumval = jQuery.parseJSON(record.Enum); //将枚举类型的json字符串转换为json对象，
                        // $(enumval).each(function(feild,text){
                        $.each(enumval, function(value, text) { //遍历json对象，形成dropdownlist需要的source对象
                            var item = {};
                            item["value"] = value;
                            item["text"] = text;
                            // alert(feild+"=="+value);
                            gridProperty[driverOrchannel].emunList[record.Field].push(item);
                        });
                    } catch (e) {

                    }
                    column["createeditor"] = function(row, column, editor) {
                        // assign a new data source to the dropdownlist.

                        editor.jqxDropDownList({
                            source: gridProperty[driverOrchannel].emunList[record.Field],
                            placeHolder: "选择进程类型:",
                            autoDropDownHeight: true,
                            displayMember: "text",
                            valueMember: "value",
                            theme: theme
                        });

                    };
                }



                column["getEditorValue"] = function(row, cellvalue, editor) {
                    // return the editor's value.
                    return editor.val();
                }

                column["cellvaluechanging"] = function(row, column, columntype, oldvalue, newvalue) {
                    // return the old value, if the new value is empty.
                    if (newvalue == "") return oldvalue;
                }

                column["cellbeginedit"] = function(row, datafield, columntype) {
                    //获取row对应的datafield的flag的ckeckbox，如果是1，返回true，如果是0，返回false
                    //如果量测启用，前面的所有项才可编辑
                    //这里只有遥测会有这样的配置约束，所以在这里直接填写了遥测dom的div对应的id。在这里取dom的owner的id。不太好弄
                    //波动 Fluc     --对应单元格返回false


                    var editableFlag = true;
              

                    return editableFlag;

                } //end cellbeginedit
                //checkbox 相关的单元格，如果checkbox没有备选中，不允许编辑
                column["cellsrenderer"] = function(row, datafield, value, defaultHtml, columnproperties) {
                    //根据 column->feild column 判断当前列。
                    var editableFlag = true;


                    if (editableFlag == false) {
                        var element = $(defaultHtml);
                        element.css('color', '#131313');
                        return element[0].outerHTML;
                    }

                    return defaultHtml;

                } //end cellsrenderer

                gridProperty[driverOrchannel].columns.push(column);
            }

            //================== 表格初始话数据加载完成了之后才初始化 tab，然后在tab的init中初始化表格
            crateGird(driverOrchannel,propertyType);
        }
    });
    dataAdapter.dataBind();

    function crateGird(driverOrchannel,propertyType) {

    var source = {
        datatype: "csv",
        datafields: gridProperty[driverOrchannel].datafields,
        url: 'defaultData/' + propertyType + '.csv'
    };

    var dataAdapter = new $.jqx.dataAdapter(source, {
        async: false,
        loadError: function(xhr, status, error) {
            alert('Error loading "' + source.url + '" : ' + error);
        }
    });

    var table = $("#"+driverOrchannel).jqxGrid({
        width: '99.5%',
        height: '285',
        theme: theme,
        editable: true,
        altrows: true,
        source: dataAdapter,
        //  selectionmode : 'singlecell', //设置选择方式
        columns: gridProperty[driverOrchannel].columns
    });


    return table;
}

}


